
//
//  LBNetWorkTool.swift
//  LBAFNetworkingTool
//
//  Created by 林彬 on 16/4/28.
//  Copyright © 2016年 linbin. All rights reserved.
//

import Foundation
import UIKit
import AFNetworking

// MARK:- 对请求格式设置成枚举
enum RequestType{
    case GET
    case POST
}

class LBNetWorkTool : AFHTTPSessionManager {
    // MARK:- 将LBNetWorkTool设置成单例
    static let shareNetWorkTool : LBNetWorkTool = {
        let tools = LBNetWorkTool()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
}

// MARK:- 封装网络工具类函数
extension LBNetWorkTool{
    func request(requestType :RequestType , urlString :String , parameters :[String:AnyObject] , finished:(result : AnyObject? , error : NSError?) ->()) {
        
        // 成功的闭包
        let successCallBack = {(task:NSURLSessionDataTask, result:AnyObject?) -> Void in
            // 成后执行的程序
            finished(result: result, error: nil)             // 执行闭包,传递参数
        }
        
        // 失败的闭包
        let failureCallBack = {(task : NSURLSessionDataTask?, error : NSError) -> Void in
            // 失败后执行的程序
            finished(result: nil, error: error)
        }
        
        
        if requestType == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}


// MARK:- 给HomeView提供网络请求方法
extension LBNetWorkTool{
    func getHomeViewNetData(offset:Int , finished : (result : AnyObject? , error : NSError?) ->()){
        // 1.获取请求的URLString
        let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
        
        // 2.获取请求的参数
        let parameters = ["offset" : "\(offset)", "limit" : "30", "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"]
        
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            // 1:判断有没有错误,有就返回错误
            if error != nil {
                finished(result: nil, error: error)
                return
            }
            
            // 2:如果result的类型不是字典,那么报data error错误
            guard let result = result as? [String : AnyObject] else {
                finished(result: nil, error: NSError(domain: "data error", code: -1011, userInfo: nil))
                return
            }
            
            // 3:都没错误,那么返回正常的数据
                // 这里返回的是result这个字典中的data key键对应的值.对应的类型是字典数组
            finished(result: result["data"] as? [[String : AnyObject]], error: nil)
        }
        
    }
}